package cn.ichiva.tushare.sdk.tushare;

import cn.ichiva.tushare.sdk.tushare.entity.TuRequest;
import cn.ichiva.tushare.sdk.tushare.entity.TuResponse;
import cn.ichiva.tushare.sdk.tushare.entity.TuTable;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import cn.ichiva.common.web.*;
import java.util.Optional;

/**
 * 读取数据
 */
@Slf4j
public abstract class AbstractTuData implements TuData {

    protected final TuConfig config;

    private TuRequest request;

    public AbstractTuData(TuConfig config){
        this.config = config;
    }

    public TuRequest getRequest() {
        return request;
    }

    public void setRequest(TuRequest request) {
        this.request = request;
    }

    public Optional<TuResponse> post(TuRequest request){
        request.setToken(config.getToken());
        try {
            String json = HttpUtils.doPost(config.getUrl(), JSON.toJSONString(request.toQuery()));
            TuResponse tuResponse = JSON.parseObject(json, TuResponse.class);
            if(null != tuResponse) return Optional.of(tuResponse);
        } catch (Exception e) {
            log.warn("拉取数据失败 api = " + request.getApi(),e);
        }
        return Optional.empty();
    }

    @Override
    public Optional<TuTable> get() {
        log.info("读取服务器数据 api = {}",request.getApi());
        Optional<TuResponse> res = post(request);
        if (res.isPresent()) {
            TuTable data = res.get().getData();
            return Optional.ofNullable(data);
        }
        return Optional.empty();
    }
}
